package com.tpc.client.modules.core.contact;

import com.tpc.client.modules.core.contact.datasource.ContactFormDS;
import com.tpc.client.modules.core.contact.datasource.ContactListDS;
import com.google.gwt.user.client.Window;
import com.smartgwt.client.data.Criteria;
import com.smartgwt.client.data.ResultSet;
import com.smartgwt.client.data.events.DataArrivedEvent;
import com.smartgwt.client.data.events.DataArrivedHandler;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.widgets.form.events.ItemKeyPressEvent;
import com.smartgwt.client.widgets.form.fields.events.ClickEvent;
import com.smartgwt.client.widgets.grid.events.CellClickEvent;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Img;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.events.ItemKeyPressHandler;
import com.smartgwt.client.widgets.form.fields.ButtonItem;
import com.smartgwt.client.widgets.form.fields.CanvasItem;
import com.smartgwt.client.widgets.form.fields.DateItem;
import com.smartgwt.client.widgets.form.fields.HiddenItem;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.SpacerItem;
import com.smartgwt.client.widgets.form.fields.StaticTextItem;
import com.smartgwt.client.widgets.form.fields.SubmitItem;
import com.smartgwt.client.widgets.form.fields.TextAreaItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.ClickHandler;
import com.smartgwt.client.widgets.grid.HoverCustomizer;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.CellClickHandler;
import com.smartgwt.client.widgets.grid.events.CellDoubleClickEvent;
import com.smartgwt.client.widgets.grid.events.CellDoubleClickHandler;
import com.smartgwt.client.widgets.grid.events.FilterEditorSubmitEvent;
import com.smartgwt.client.widgets.grid.events.FilterEditorSubmitHandler;
import com.smartgwt.client.widgets.tab.Tab;
import com.smartgwt.client.widgets.tab.TabSet;
import com.tpc.client.systeme.core.Systeme;
import com.tpc.client.systeme.core.TPCT_MODULE;
/**
 * @version 0.0.1
 * @author frederic.fortin
 * @modified 2010-08-15
 */

public class ContactUI implements TPCT_MODULE {
    Systeme systeme;
    String MODULEID;
    
    Canvas cnvEmpty = new Canvas();
    
    ListGrid GRID_LIST = new ListGrid();
    DynamicForm FORM_EDIT = new DynamicForm();

    ContactListDS CTCDS = new ContactListDS("CTCDS");
    ContactFormDS CTC_FORM_DS = new ContactFormDS("CTC_FORM_DS");

    ListGrid GRID_MINI_ADDRESS = new ListGrid();
    ListGrid GRID_MINI_PHONE = new ListGrid();
    ListGrid GRID_MINI_IDENTITY = new ListGrid();
    ListGrid GRID_MINI_DEVICE = new ListGrid();
    ListGrid GRID_MINI_TICKET = new ListGrid();

    Boolean isUiLoaded = false;
    Boolean isListBuild = false;
    Boolean isListFetch = false;
    Boolean isFormBuild = false;
    Boolean isFormFetch = false;
    Boolean isMiniListeAddressBuilded = false;
    Boolean isMiniListePhoneBuilded = false;
    Boolean isMiniListeIdentityBuilded = false;
    Boolean isMiniListeDeviceBuilded = false;
    Boolean isMiniListeTicketBuilded = false;

    HiddenItem hitOrganisationIdContact;
    TabSet tabsetContactMini = new TabSet();
    
    public Canvas loadUI(Systeme systemParam,String MODULEIDp) {
        if (!isUiLoaded) {
            systeme = systemParam;
            MODULEID = MODULEIDp;
            cnvEmpty = systeme.getTabpaneTemplate(cnvEmpty);
            cnvEmpty.setID("CANVAS_CONTACT");
            cnvEmpty.addChild(getList());
            isUiLoaded = true;
        }
        return cnvEmpty;
    }

    public void buildList() {
        if (!isListBuild) {
            GRID_LIST = systeme.getGridTemplate(GRID_LIST);
            
            CTCDS.setObjects(systeme);
            GRID_LIST.setDataSource(CTCDS);

            ListGridField fldContactId = new ListGridField("contact_liste_id");
            fldContactId.setHidden(Boolean.TRUE);
            ListGridField fldContactName = new ListGridField("contact_liste_name", "Nom");
            fldContactName.setHoverCustomizer(new HoverCustomizer() {
                public String hoverHTML(Object value, ListGridRecord record, int rowNum, int colNum) {
                    String strHover = "<table width=200><tr><td valign=top>notes: </td><td>"+record.getAttribute("contact_liste_notes")+"</td></tr></table>";
                    return strHover;
                }
            });
            ListGridField fldContactDescription = new ListGridField("contact_liste_notes");
            fldContactDescription.setHidden(Boolean.TRUE);
            ListGridField fldContactOrganisation = new ListGridField("contact_liste_organisation");
            fldContactOrganisation.setHidden(Boolean.TRUE);
            ListGridField fldContactMailto = new ListGridField("contact_liste_mailto","Courriel");
            fldContactMailto.setHidden(Boolean.FALSE);        
            ListGridField fldContactPhone = new ListGridField("contact_liste_phone", "Téléphone", 100);
            ListGridField fldContactUsernameWindows = new ListGridField("contact_liste_usernamewindows", "Username Windows", 100);
            ListGridField fldContactOffice = new ListGridField("contact_liste_office", "Bureau", 100);
            ListGridField fldContactComputer = new ListGridField("contact_liste_computer", "Ordinateur", 100);
            ListGridField fldContactMobiledevice = new ListGridField("contact_liste_mobiledevice", "Appareil mobile", 100);

            GRID_LIST.setFields(fldContactId,fldContactName,fldContactDescription,fldContactOrganisation,fldContactMailto,fldContactPhone,fldContactUsernameWindows,
                                fldContactOffice,fldContactComputer,fldContactMobiledevice);

            GRID_LIST.addCellClickHandler(new CellClickHandler() {
                public void onCellClick(CellClickEvent event) {
                    systeme.startLoading();
                    ListGridRecord record =  event.getRecord();
                    int colNum = event.getColNum();
                    String fieldName = GRID_LIST.getFieldName(colNum);
                    if (fieldName.equals("contact_liste_mailto")) {
                        String strUrl = record.getAttribute("contact_liste_mailto");
                        if (strUrl != null) {
                            if (strUrl.length() > 4) {
                                strUrl = "mailto:"+strUrl+"?bcc=krypton@tpctechnologies.net";
                                com.google.gwt.user.client.Window.open(strUrl,"_self",null);
                            }
                            else {
                                SC.say("Courriel invalide.");
                                systeme.stopLoading();
                            }
                        }
                        else {
                            SC.say("Courriel invalide.");
                            systeme.stopLoading();
                        }
                    }
                }
            });

            GRID_LIST.addCellDoubleClickHandler(new CellDoubleClickHandler() {
                public void onCellDoubleClick(CellDoubleClickEvent event) {
                    systeme.startLoading();
                    final ListGridRecord record = event.getRecord();
                    loadForm(record);
                }
            });

            GRID_LIST.addFilterEditorSubmitHandler(new FilterEditorSubmitHandler() {
                public void onFilterEditorSubmit(FilterEditorSubmitEvent event) {
                    ResultSet rs = GRID_LIST.getResultSet();
                    rs.addDataArrivedHandler(new DataArrivedHandler() {
                        public void onDataArrived(DataArrivedEvent event) {
                            systeme.getAppBar().getTab("CONTACTS").setTitle("Usagers ("+GRID_LIST.getResultSet().getLength()+")");
                        }
                    });
                }
            });
        }
        isListBuild = true;
    }

    public ListGrid getList() {
        if (!isListBuild) { buildList(); }
        return GRID_LIST;
    }

    public void loadList() {
        if (!isListBuild) { buildList(); }
        if (!isListFetch) {
            GRID_LIST.invalidateCache();
            GRID_LIST.fetchData();
            isListFetch = true;
        }
    }

    public void buildForm() {
        if (!isFormBuild) {
                FORM_EDIT = systeme.getFormTemplate(FORM_EDIT);
                FORM_EDIT.setNumCols(4);
                FORM_EDIT.setCellBorder(0);
                FORM_EDIT.setColWidths(450,200,200,100);
                FORM_EDIT.addItemKeyPressHandler(new ItemKeyPressHandler() {
                    public void onItemKeyPress(ItemKeyPressEvent event) {
                        FORM_EDIT.getItem("changedHandler_ctc").setValue("true");
                    }
                });

                CTC_FORM_DS.setObjects(GRID_LIST,FORM_EDIT,systeme);
                FORM_EDIT.setDataSource(CTC_FORM_DS);

                    CanvasItem canvasCloseButton = new CanvasItem();
                    canvasCloseButton.setColSpan(4);
                    canvasCloseButton.setWidth("100%");
                    canvasCloseButton.setHeight(24);
                    canvasCloseButton.setAlign(Alignment.RIGHT);
                    canvasCloseButton.setShowTitle(Boolean.FALSE);

                        Img imgCloseButton = new Img("closeForm.png",22,22);
                        imgCloseButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
                            public void onClick(com.smartgwt.client.widgets.events.ClickEvent event) {
                                FORM_EDIT.clearErrors(Boolean.TRUE);
                                FORM_EDIT.clearValues();
                                systeme.getAppBar().updateTab(systeme.getAppBar().getTab("CONTACTS"),getList());
                            }
                        });

                    canvasCloseButton.setCanvas(imgCloseButton);

                    HiddenItem hitContactId = new HiddenItem("contact_form_id");

                    final TextItem fitFirstNameContact = new TextItem("contact_form_firstname","Prénom");
                    fitFirstNameContact.setWidth(425);
                    fitFirstNameContact.setHeight(28);
                    fitFirstNameContact.setColSpan(1);
                    fitFirstNameContact.setTextBoxStyle("defaultTextBoxItem");
                    fitFirstNameContact.setTitleStyle("defaultTextBoxTitle");

                    SelectItem sitTitleContact = new SelectItem("contact_form_title", "Salutation");
                    //sitTitleContact.setOptionDataSource(systeme.getTITLEDS());
                    sitTitleContact.setDisplayField("titleContactName");
                    sitTitleContact.setValueField("titleContactId");
                    sitTitleContact.setAutoFetchData(Boolean.TRUE);
                    sitTitleContact.setWidth(200);
                    sitTitleContact.setHeight(28);
                    sitTitleContact.setColSpan(1);
                    sitTitleContact.setTextBoxStyle("defaultDropBoxItem");
                    sitTitleContact.setTitleStyle("defaultTextBoxTitle");

                    SelectItem sitLanguageContact = new SelectItem("contact_form_langue", "Langue");
                    //sitLanguageContact.setOptionDataSource(systeme.getLANGUEDS());
                    sitLanguageContact.setDisplayField("languageContactName");
                    sitLanguageContact.setValueField("languageContactId");
                    sitLanguageContact.setAutoFetchData(Boolean.TRUE);
                    sitLanguageContact.setWidth(300);
                    sitLanguageContact.setHeight(28);
                    sitLanguageContact.setColSpan(2);
                    sitLanguageContact.setTitleStyle("defaultTextBoxTitle");
                    sitLanguageContact.setTextBoxStyle("defaultDropBoxItem");

                    final TextItem fitLastNameContact = new TextItem("contact_form_lastname","Nom de famille");
                    fitLastNameContact.setColSpan(1);
                    fitLastNameContact.setHeight(28);
                    fitLastNameContact.setWidth(425);
                    fitLastNameContact.setTextBoxStyle("defaultTextBoxItem");
                    fitLastNameContact.setTitleStyle("defaultTextBoxTitle");

                    final DateItem ditBirthdayContact = new DateItem("birthday_contact", "Anniversaire");
                    ditBirthdayContact.setUseTextField(Boolean.TRUE);
                    ditBirthdayContact.setColSpan(1);
                    ditBirthdayContact.setHeight(28);
                    ditBirthdayContact.setWidth(200);
                    ditBirthdayContact.setTitleStyle("defaultTextBoxTitle");
                    ditBirthdayContact.setTextBoxStyle("defaultTextBoxItem");

                    SelectItem sitGroupe = new SelectItem("contact_form_groupe","Groupe");
                    sitGroupe.setWidth(300);
                    sitGroupe.setColSpan(2);
                    sitGroupe.setHeight(28);
                    //sitGroupe.setOptionDataSource(systeme.getGROUPEDS());
                    sitGroupe.setDisplayField("groupeName");
                    sitGroupe.setValueField("groupeId");
                    sitGroupe.setAutoFetchData(Boolean.TRUE);
                    sitGroupe.setTextBoxStyle("defaultDropBoxItem");
                    sitGroupe.setTitleStyle("defaultTextBoxTitle");

                    TextAreaItem taiNotes = new TextAreaItem("contact_form_notes","Notes");
                    taiNotes.setWidth("100%");
                    taiNotes.setHeight(90);
                    taiNotes.setColSpan(4);
                    taiNotes.setDefaultValue("");
                    taiNotes.setTitleStyle("defaultTextBoxTitle");
                    taiNotes.setTextBoxStyle("defaultTextBoxItem");

                    CanvasItem cniMiniListe= new CanvasItem();
                    cniMiniListe.setShowTitle(Boolean.FALSE);
                    cniMiniListe.setColSpan(4);
                    cniMiniListe.setWidth("100%");
                    cniMiniListe.setHeight("*");
                        TabSet tabMiniListe = new TabSet();
                            Tab tabAddress = new Tab("Adresses");
                            tabAddress.setID("CONTACT_MINI_ADDRESS");
                            tabAddress.setPane(getMiniListeAddress());
                            Tab tabPhone = new Tab("Téléphones");
                            tabPhone.setID("CONTACT_MINI_PHONE");
                            tabPhone.setPane(getMiniListePhone());
                            Tab tabIdentity = new Tab("Identités");
                            tabIdentity.setID("CONTACT_MINI_IDENTITY");
                            tabIdentity.setPane(getMiniListeIdentity());
                            Tab tabDevices = new Tab("Appareils");
                            tabDevices.setID("CONTACT_MINI_DEVICES");
                            tabDevices.setPane(getMiniListeDevice());
                            Tab tabTickets = new Tab("Requêtes");
                            tabTickets.setID("CONTACT_MINI_TICKETS");
                            tabTickets.setPane(getMiniListeTicket());

                        tabMiniListe.setTabs(tabAddress,tabPhone,tabIdentity,tabDevices,tabTickets);
                    cniMiniListe.setCanvas(tabMiniListe);

                    SpacerItem pushDown = new SpacerItem();
                    pushDown.setColSpan(8);
                    pushDown.setHeight(1);

                    ButtonItem bitPrint = new ButtonItem("PRINT_CONTACT", "IMPRIMER");
                    bitPrint.setWidth(75);
                    bitPrint.setColSpan(1);
                    bitPrint.setStartRow(Boolean.TRUE);
                    bitPrint.setEndRow(Boolean.FALSE);
                    bitPrint.addClickHandler(new ClickHandler() {
                        public void onClick(ClickEvent event) {
                            Window.print();
                        }
                    });

                    SpacerItem sitHorizontal = new SpacerItem();
                    sitHorizontal.setWidth(205);

                    StaticTextItem stiCreatedDate = new StaticTextItem("createddate_contact");
                    stiCreatedDate.setShowTitle(Boolean.FALSE);
                    stiCreatedDate.setColSpan(1);
                    stiCreatedDate.setWidth(125);
                    stiCreatedDate.setAlign(Alignment.RIGHT);
                    stiCreatedDate.setTextBoxStyle("createdOn");

                    SpacerItem spiBetweenDate = new SpacerItem();
                    spiBetweenDate.setWidth(25);
                    spiBetweenDate.setHeight(22);

                    StaticTextItem stiModifiedDate = new StaticTextItem("modifieddate_contact");
                    stiModifiedDate.setShowTitle(Boolean.FALSE);
                    stiModifiedDate.setColSpan(1);
                    stiModifiedDate.setWidth(125);
                    stiModifiedDate.setTextBoxStyle("createdOn");

                    ButtonItem bitCancel = new ButtonItem("CANCEL_CONTACT", "ANNULER");
                    bitCancel.setWidth(75);
                    bitCancel.setAlign(Alignment.RIGHT);
                    bitCancel.setStartRow(Boolean.FALSE);
                    bitCancel.setEndRow(Boolean.FALSE);
                    bitCancel.addClickHandler(new ClickHandler() {
                        public void onClick(ClickEvent event) {
                            systeme.getAppBar().updateTab(systeme.getAppBar().getTab("CONTACTS"),getList());
                            FORM_EDIT.clearErrors(Boolean.TRUE);
                            FORM_EDIT.clearValues();
                        }
                    });

                    SubmitItem sitSave = new SubmitItem("SAVE_CONTACT", "ENREGISTRER");
                    sitSave.setWidth(85);
                    sitSave.setAlign(Alignment.CENTER);
                    sitSave.setStartRow(Boolean.FALSE);
                    sitSave.setEndRow(Boolean.TRUE);

                    HiddenItem hitValuesChanged = new HiddenItem("changedHandler_ctc");
                    hitValuesChanged.setValue("false");

                    HiddenItem hitSaveOnExit = new HiddenItem("saveOnExit");
                    hitSaveOnExit.setValue("false");

                    SpacerItem pushUp = new SpacerItem();
                    pushUp.setColSpan(4);
                    pushUp.setHeight(12);

                FORM_EDIT.focusInItem("organisation_contact");

                FORM_EDIT.setFields(canvasCloseButton,fitFirstNameContact,sitTitleContact,sitLanguageContact,fitLastNameContact,ditBirthdayContact,sitGroupe,taiNotes,
                        cniMiniListe,pushDown,bitPrint,stiCreatedDate,bitCancel,sitSave,hitValuesChanged,hitSaveOnExit,hitContactId,pushUp);
            isFormBuild = true;
        }
    }

    public void create(ListGridRecord record) {
        getForm().getItem("changedHandler_ctc").setValue("false");
        getForm().editNewRecord();
        getForm().clearErrors(true);
        getForm().getItem("id_contact").setValue(0);
        getForm().getItem("organisationId_contact").setValue(record.getAttributeAsInt("organisation_id"));
        getForm().getItem("organisation_contact").setValue(record.getAttribute("organisation_name"));
        systeme.stopLoading();
    }

    public void loadForm(ListGridRecord record) {
        getForm().clearValues();
        getForm().clearErrors(Boolean.TRUE);
        String strId = record.getAttribute("contact_liste_id");
        getForm().fetchData(new Criteria("id_contact",strId));
        isFormFetch = true;
        systeme.getAppBar().updateTab(systeme.getAppBar().getTab("CONTACTS"),getForm());
    }

    public DynamicForm getForm() {
        if (!isFormBuild) { buildForm(); }
        return FORM_EDIT;
    }
    
    public DynamicForm showAndCreate(ListGridRecord record) {
        create(record);
        return getForm();
    }

    /** Mini-Listes **/
    public void buildMiniListeAddress() {
        if (!isMiniListeAddressBuilded) {

            isMiniListeAddressBuilded = true;
        }
    }

    public ListGrid getMiniListeAddress() {
        if (!isMiniListeAddressBuilded) { buildMiniListeAddress(); }
        return GRID_MINI_ADDRESS;
    }

    public void buildMiniListePhone() {
        if (!isMiniListePhoneBuilded) {

            isMiniListePhoneBuilded = true;
        }
    }

    public ListGrid getMiniListePhone() {
        if (!isMiniListePhoneBuilded) { buildMiniListePhone(); }
        return GRID_MINI_PHONE;
    }

    public void buildMiniListeIdentity() {
        if (!isMiniListeIdentityBuilded) {

            isMiniListeIdentityBuilded = true;
        }
    }

    public ListGrid getMiniListeIdentity() {
        if (!isMiniListeIdentityBuilded) { buildMiniListeIdentity(); }
        return GRID_MINI_IDENTITY;
    }

    public void buildMiniListeDevice() {
        if (!isMiniListeDeviceBuilded) {

            isMiniListeDeviceBuilded = true;
        }
    }

    public ListGrid getMiniListeDevice() {
        if (!isMiniListeDeviceBuilded) { buildMiniListeDevice(); }
        return GRID_MINI_DEVICE;
    }

    public void buildMiniListeTicket() {
        if (!isMiniListeTicketBuilded) {

            isMiniListeTicketBuilded = true;
        }
    }

    public ListGrid getMiniListeTicket() {
        if (!isMiniListeTicketBuilded) { buildMiniListeTicket(); }
        return GRID_MINI_TICKET;
    }

}